package gov.pbc.nn.kjgl.maintenance.handler;

import gov.pbc.nn.kjgl.maintenance.entity.SysChange;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.HistoryProcessInstance;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.ProcessEventHandler;

@Component(SysChangeProcessEventHandler.BEAN_ID)
public class SysChangeProcessEventHandler implements ProcessEventHandler {

	public static final String BEAN_ID = "gov.pbc.nn.kjgl.maintenance.handler.SysChangeProcessEventHandler";

	@Override
	public void end(ProcessInstance arg0, Context arg1) {

	}

	@Override
	public void start(ProcessInstance pi, Context context) {
		long pId = pi.getParentId();
		if (pId == 0)
			return;
		SysChange change = (SysChange) context.getProcessService()
				.getProcessVariable("sysChange", pId);
		String cto = (String) context.getProcessService().getProcessVariable(
				"cto", pId);
		if (change != null) {
			pi.setBusinessId(change.getId());
			pi.setPromoter(ContextHolder.getLoginUserName());
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("sysId", change.getSysId());
			variables.put("cto", cto);
			variables.put("agree", 1);
			variables.put("isBusinessStartProcess", false);
			context.getProcessService().saveProcessVariables(pi.getId(),
					variables);
			context.getSession().saveOrUpdate(pi);

			HistoryProcessInstance hpi = (HistoryProcessInstance) context
					.getSession().createCriteria(HistoryProcessInstance.class)
					.add(Restrictions.eq("processInstanceId", pi.getId()))
					.uniqueResult();
			hpi.setBusinessId(pi.getBusinessId());
			hpi.setPromoter(pi.getPromoter());
			context.getSession().update(hpi);
		}
	}

}
